import poker_dealing

class HeartGame_server:
    def __init__(self):
        self.total_scores = [0, 0, 0, 0] #四名玩家的总分
        self.game_scores = [0, 0, 0, 0] #四名玩家当前小局的分数
        self.cards_in_round = [None, None, None, None] #每一轮四名玩家出的牌
        self.first_player = 0 #每一轮第一个出牌的玩家
        self.current_round = 1 #记录现在是第几轮
    def reset_game_scores(self):
        self.game_scores = [0, 0, 0, 0]

    def reset_total_scores(self):
        self.total_scores = [0, 0, 0, 0]

    def reset_cards_in_round(self):
        self.cards_in_round = [None, None, None, None]

    def score_of_card(self, card): #判断牌的分数
        suit = card[0]
        rank = card[1]
        if suit == "♥":
            return 1
        elif suit == "♠" and rank == 'Q':
            return 13
        else:
            return 0

    def judge_larger_card(self, a, b): #给定a,b两个点数（A~K)，返回a的点数是否大于b，默认两个点数不一样大
        ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
        for r in ranks:
            if r == b:
                return True
            elif r == a:
                return False
        return -1

    def judge_largest_card(self): #判断需要得分的玩家，返回其座位号和得分
        current_suit = self.cards_in_round[self.first_player][0]
        largest_position = self.first_player #假设第一个出牌的玩家牌是最大的
        score = 0
        for i, c in enumerate(self.cards_in_round):
            score += self.score_of_card(c)
            if i == self.first_player:
                continue
            suit = c[0]
            if suit != current_suit:
                continue
            rank = c[1]
            if self.judge_larger_card(rank, self.cards_in_round[largest_position][1]):
                largest_position = i
        return largest_position, score

    def end_game(self): #小局游戏结束
        if 26 in self.game_scores: #如果有人击中月亮
            self.game_scores = [26 if s == 0 else 0 for s in self.game_scores]
        self.total_scores = [x + y for x, y in zip(self.total_scores, self.game_scores)]
        msg = {
            "type": "game end",
            "content": self.total_scores
        }
        self.reset_game_scores()
        return msg